﻿using System;
using System.Collections.Generic;
using global::GoGameClient.script.global;
using Godot;
using Newtonsoft.Json;

namespace GoGameClient.script.resources;

public class TerrainResources : IResources
{
    private string Terrain { get; set; } = ResourcesControl.RootPath + "terrain";

    private AStarGrid2D AStarGrid2D { get; }

    public TerrainResources(int id)
    {
        var resource = (Json)GD.Load($"{Terrain}/{id}.json");
        if (resource == null)
        {
            return;
        }

        AStarGrid2D = new AStarGrid2D();
        var mapInfo = ResourcesControl.Instance().GetMapInfo(id);
        if (mapInfo == null)
        {
            throw new Exception($"获取文件地图信息失败 id:{id}");
        }

        AStarGrid2D.Region = new Rect2I(
            0,
            0,
            mapInfo.Col * mapInfo.MapColNum / 20,
            mapInfo.Row * mapInfo.MapRowNum / 20);
        AStarGrid2D.Update();
        var terrainInfo = JsonConvert.DeserializeObject<List<TerrainInfo>>(Json.Stringify(resource.Data));
        foreach (var info in terrainInfo)
        {
            AStarGrid2D.SetPointSolid(new Vector2I(info.X, info.Y));
        }
    }


    public AStarGrid2D GetAStarGrid2D()
    {
        return AStarGrid2D;
    }

    public string GetPath()
    {
        return Terrain;
    }

    public void SetPath(string path)
    {
        Terrain = ResourcesControl.RootPath + path;
    }
}

public class TerrainInfo
{
    public int X { get; set; }
    public int Y { get; set; }
}